package mysql

import (
	"database/sql"
	"github.com/jmoiron/sqlx"
)

type SysProjectEntity struct {
	ProjectId     int64          `db:"project_id"`
	ProjectName   sql.NullString `db:"project_name"`
	ProjectDesc   sql.NullString `db:"project_desc"`
	ProjectStatus int64          `db:"project_status"`
	IsEnable      int64          `db:"is_enable"`
}

type SysProjectDao struct{}

func (s *SysProjectDao) Insert(tx *sqlx.Tx, e *SysProjectEntity) (*int64, error) {
	query := "INSERT INTO sys_project " +
		"(" +
		"project_name, " +
		"project_desc, " +
		"project_status, " +
		"is_enable, " +
		") VALUES (" +
		":project_name, " +
		":project_desc, " +
		":project_status, " +
		":is_enable, " +
		")"

	rs, err := tx.NamedExec(query, e)
	if err != nil {
		return nil, err
	}
	id, err := rs.LastInsertId()
	if err != nil {
		return nil, err
	}
	return &id, nil
}

func (s *SysProjectDao) FindById(db *sqlx.DB, id *int64) (*SysProjectEntity, error) {
	query := "SELECT " +
		"project_id, " +
		"project_name, " +
		"project_desc, " +
		"project_status, " +
		"is_enable " +
		"FROM sys_project " +
		"WHERE project_id = :project_id"
	rs := &SysProjectEntity{}
	err := db.Get(rs, query, id)
	if err != nil {
		return nil, err
	}
	return rs, nil
}

func (s *SysProjectDao) ListAll(db *sqlx.DB) (*[]SysProjectEntity, error) {
	query := "SELECT " +
		"project_id, " +
		"project_name, " +
		"project_desc, " +
		"project_status, " +
		"is_enable " +
		"FROM sys_project"
	rs := &[]SysProjectEntity{}
	err := db.Select(rs, query, nil)
	if err != nil {
		return nil, err
	}
	return rs, nil
}
